/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.storage.api;

import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.storage.common.ServerResponse;
import com.jeesite.modules.storage.service.OrderService;
import com.jeesite.modules.storage.util.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 支付宝Controller
 */
@RestController(value = "apialipay")
@RequestMapping(value = "/api/alipay")
public class AlipayController extends APIController {
    @Autowired
    private OrderService orderService;

    /**
     * app支付
     *
     * @param orderId 订单Id
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "pay/app")
    public ServerResponse<Object> appPay(@RequestParam(value = "platform") String platform, @RequestParam(value = "orderId") String orderId) throws Exception {
        return ServerResponse.createBySuccess(200, orderService.doPay(orderId, platform, "Alipay", null));
    }

    /**
     * 异步同步【支付】
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "pay/notify")
    public String payNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String outTradeNo = request.getParameter("out_trade_no");
        String tradeStatus = request.getParameter("trade_status");
        if (StringUtils.isBlank(outTradeNo) || StringUtils.isBlank(tradeStatus) || !tradeStatus.equals("TRADE_SUCCESS")) {
            return "fail";
        }
        if (orderService.payHandle(WebUtil.getOrderIdByTradeNo(outTradeNo),null) == 200) {
            return "success";
        }
        return "fail";
    }

    /**
     * 异步同步【退款】
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "refund/notify")
    public String refundNotify(HttpServletRequest request) throws Exception {
        String outTradeNo = request.getParameter("out_trade_no");
        String tradeStatus = request.getParameter("trade_status");
        if (StringUtils.isBlank(outTradeNo) || StringUtils.isBlank(tradeStatus) || !tradeStatus.equals("TRADE_SUCCESS")) {
            return "";
        }
        if (orderService.refundHandle(WebUtil.getOrderIdByTradeNo(outTradeNo)) == 200) {
            return "success";
        }
        return "fail";
    }
}
